package com.example.yibu.modelConfig.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

public class LimitedThreadPool {
    private static final Logger log = Logger.getLogger(LimitedThreadPool.class.getName());

    private static final Integer CORE_POOL_SIZE = 5; //核心线程数
    private static final Integer MAXIMUM_POOL_SIZE = 10; //最大线程数
    private static final int KEEP_ALIVE = 60; //空闲线程的最长存活时间
    private static final TimeUnit TIME_UNIT =  TimeUnit.SECONDS; //时间单位
    private static final BlockingQueue<Runnable> WORKQUEUE = new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);//工作队列-阻塞队列
    private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.DiscardPolicy(); //拒绝策略
    private static final ThreadFactory mThreadFactory = new ThreadFactory() {
        //原子操作级别的整数，初始值是1
        private final AtomicInteger mCount = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            //PcmRecorder.bandCpu();
            Thread thread = new Thread(r, "Task #" + mCount.getAndIncrement()); //线程名，前缀固定，后缀自增长
            thread.setPriority(Thread.NORM_PRIORITY - 1);   //正常优先级
            return thread;
        }
    };
    private static final ThreadPoolExecutor executor;
    public static ThreadPoolExecutor createPool(){
        return executor;
    }

    static {
        executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE,
                TIME_UNIT,
                WORKQUEUE,
                mThreadFactory,
                HANDLER
        );
    }

    public static void shutdownExecutor(ThreadPoolExecutor executor) {
        // 请求停止所有工作线程
        executor.shutdown();
        // 尝试等待所有任务完成
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                log.warning("部分任务在60秒内未能完成，开始尝试强制关闭...");
                // 尝试中断所有正在执行的任务
                executor.shutdownNow();
                // 再次等待所有任务完成
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    log.severe("一些任务在强制关闭后仍未能完成，线程池可能未完全关闭。");
                } else {
                    log.info("所有任务已通过强制关闭成功完成。");
                }
            } else {
                log.info("所有任务已正常完成。");
            }
        } catch (InterruptedException ie) {
            // 重新设置中断标志，并尝试强制关闭线程池
            log.severe("等待任务完成时被中断，正在进行强制关闭...");
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.log(java.util.logging.Level.SEVERE, "关闭线程池时发生未知错误", e);
            throw new RuntimeException("关闭线程池时发生错误: " + e.getMessage(), e);
        }
    }

}
